package com.yyk.yykywd.util

import android.content.Context
import android.text.*
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.text.style.UnderlineSpan
import android.view.View
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.yyk.yykywd.R

/**
 * 文件描述：
 * Created by guo on 2019-12-20.
 */
fun setTextForegroundColor(context: Context, tv: TextView, setMessage: String, message: String){
    val start = message.indexOf(setMessage)
    setTextColor(context, tv, start, start + setMessage.length, message)
}

fun setTextColor(context: Context, tv: TextView, start: Int, end: Int, message: String) {
    val builder = SpannableStringBuilder(message)
    if (start == -1) {
        tv.text = message
    }else {
        builder.setSpan(ForegroundColorSpan(ContextCompat.getColor(context, R.color.blue_51)), start, end, Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
        tv.text = builder
    }
}

fun setTextClick(context: Context, tv: TextView, setMessage: String, message: String, mListener:(() -> Unit)) {
    val protocol = SpannableString(message)
    val start = message.indexOf(setMessage)
    protocol.setSpan(object : ClickableSpan() {
        override fun onClick(widget: View) {
            mListener.invoke()
        }
    }, start, start + setMessage.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
    protocol.setSpan(object : UnderlineSpan() {
        override fun updateDrawState(ds: TextPaint) {
            super.updateDrawState(ds)
            ds.color = ContextCompat.getColor(context, R.color.blue_51) //设置颜色
        }
    }, start, start + setMessage.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
    tv.text = protocol
    tv.movementMethod = LinkMovementMethod.getInstance()
    //设置文字点击高亮颜色为透明
    tv.highlightColor = ContextCompat.getColor(context, android.R.color.transparent)
}